summaryrefslogtreecommitdiffstats
path: root/src/generate_parse_functions.php
blob: 23eca4986e64f9376ca44fdc89dabc5011063c6b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env php
<?php
$s = [
	"user" => [
		"members" => [
			"username" => [
				"json" => "username",
				"type" => "string"
			],
			"discriminator" => [
				"json" => "discriminator",
				"type" => "number"
			]
		]
	],
	"channel" => [
		"members" => [
			"name" => [
				"json" => "name",
				"type" => "string"
			],
			"type" => [
				"json" => "type",
				"type" => "number"
			]
		],
		"parsing" => [
			"checks" => [
				'DC_CHANNEL_SUPPORTED(cJSON_GNV(cJSON_GOI(s, "type")))'
			],
			"code" => <<<HEREDOC
				cJSON_AFE(o, cJSON_GOI(s, "recipient_ids")) {
					char * c = cJSON_GSV(o);
					if (!c)
						continue;
					struct dc_user * u = dc_user_init();
					u->id = strtoull(st, NULL, 10);
					u = dc_addr_user(p, DC_ISAE(p->users), u, DC_MAY_FREE);
					dc_add_user(DC_ISAE(ch->users), u, 0);
				}
			HEREDOC,
		]
	]
];
foreach ($s as $name => $fields) {
	echo <<<HEREDOC
	struct dc_$name * dc_parse_$name (struct dc_program * p, const cJSON * s) {
		cJSON * o;
		if (!s) /* in case cJSON_GOIx returns NULL */
			return NULL;
		char * c = cJSON_GSV(cJSON_GOI(s, "id"));
		if (!c)
			return NULL;
		unsigned long long int i = strtoull(c, NULL, 10);
		struct dc_$name * n = dc_find_$name(p->{$name}s, p->{$name}s_length, i);

	HEREDOC;
	if (isset($fields["parsing"]) && sizeof($fields["parsing"]["checks"])) {
		echo "	if (";
		$arr = $fields["parsing"]["checks"];
		foreach ($arr as $n => $check) {
			$or = "";
			$end = "";
			if ($n != array_key_first($arr))
				$or = "			|| ";
			if ($n != array_key_last($arr))
				$end = PHP_EOL;
			echo "$or!($check)$end";
		}
		echo <<<HEREDOC
		)
				return NULL;

		HEREDOC;
	}
	echo <<<HEREDOC
		if (!n) {
			n = dc_{$name}_init();
			n->id = i;
			dc_addr_$name(p, DC_ISAE(p->{$name}s), n, 0);
		}

	HEREDOC;
	if (isset($fields["parsing"]))
		echo $fields["parsing"]["code"] . PHP_EOL;
	foreach ($fields["members"] as $member => $meta) {
		switch ($meta["type"]) {
			case "string":
				echo <<<HEREDOC
					if ((c = cJSON_GSV(cJSON_GOI(s, "{$meta["json"]}")))) {
						free(n->$member);
						n->$member = strdup(c);
					}

				HEREDOC;
				break;
			case "number":
				echo <<<HEREDOC
					if ((o = cJSON_GOI(s, "{$meta["json"]}")))
						n->$member = cJSON_GNV(o);

				HEREDOC;
				break;
		}
	}
	echo <<<HEREDOC
		return n;
	}

	HEREDOC;
}
?>